package com.qinghe.utils.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json字符串、对象、List转换工具类.
 * 
 * @author longfei
 */
public class JsonUtil {

	private static final ObjectMapper mapper;

	static {
		mapper = new ObjectMapper();
	}

	/**
	 * Object转json字符串
	 * 
	 * @param object
	 * 
	 * @return String
	 * @author longfei
	 */
	public String toJson(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (Exception e) {
			throw new RuntimeException("转换json字符失败!");
		}
	}

	/**
	 * json字符串转换成对象
	 * 
	 * @param json json格式字符串
	 * @param c 元素类
	 * 
	 * @return T
	 * @author longfei
	 */
	public <T> T toObject(String json, Class<T> c) {
		try {
			return mapper.readValue(json, c);
		} catch (IOException e) {
			throw new RuntimeException("将json字符转换为对象时失败!");
		}
	}

	/**
	 * json字符串转换成泛型List
	 * 
	 * @param json json格式字符串
	 * @param c 元素类
	 * 
	 * @return List<T>
	 * @author longfei
	 */
	@SuppressWarnings("unchecked")
	public <T> List<T> toList(String json, Class<T> c) {
		try {
			return (List<T>) mapper.readValue(json, getCollectionType(ArrayList.class, c));
		} catch (IOException e) {
			throw new RuntimeException("将json字符转换为对象时失败!");
		}
	}

	/**
	 * 获取泛型的Collection Type
	 * 
	 * @param collectionClass 泛型的Collection
	 * @param elementClasses 元素类
	 * 
	 * @return JavaType Java类型
	 * @author longfei
	 */
	private JavaType getCollectionType(Class<?> collectionClass,
			Class<?>... elementClasses) {
		return new ObjectMapper().getTypeFactory().constructParametricType(
				collectionClass, elementClasses);
	}

}
